package com.sh.ndt.login.mbean;

import com.sh.ndt.common.CreateXML;
import com.sh.ndt.common.SessionObjects;
import com.sh.ndt.common.URL;
import com.sh.ndt.common.WSCaller;
import com.sh.ndt.common.entity.EmailContent;
import com.sh.ndt.common.entity.LoginParam;
import com.sh.ndt.exception.WebServiceException;
import com.sh.ndt.user.entity.User;
import com.sh.ndt.user.entity.UserEntitlement;
import com.sh.ndt.user.entity.UserParam;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import org.apache.log4j.Logger;

/**
 * This class acts as both event handler and controller.
 *
 * Meaning, for web events, this class provides the data as bean and for web
 * submission this class acts as controller that calls the services.
 *
 * The scope definition can also be controlled in this class.
 */
@ManagedBean
@SessionScoped
public class LoginBean implements Serializable {

    /**
     *
     */
    private static final long serialVersionUID = 1L;

    private static final Logger LOGGER = Logger.getLogger(LoginBean.class);


    private String firstName = "First Name";
    private String lastName = "Last Name";
    private String guestEmailId = "email";
    private String guestFullName = "Full Name";
    private String newUserFirstName = "First Name";
    private String newUserLastName = "Last Name";
    private String newUserEmailId = "Your Email";
    private String newUserPassword = null;
      

    String emailId = "enter email";
    String password = "password";
    String errorMessage = null;
    String usersFullName = null;

    public String getEmailId() {
        return emailId;
    }

    public void setEmailId(String emailId) {
        this.emailId = emailId;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getErrorMessage() {
        return errorMessage;
    }

    public void setErrorMessage(String errorMessage) {
        this.errorMessage = errorMessage;
    }

    public String getUsersFullName() {
        return usersFullName;
    }

    public void setUsersFullName(String usersFullName) {
        this.usersFullName = usersFullName;
    }

    public String addProspectiveUser() {

        LOGGER.debug("Inside addProspectiveUser()" + getGuestEmailId() + " : " + getGuestFullName());

        return "guestUsersDashboard.xhtml?faces-redirect=true";
    }

    public void signupNewUser() {
      LOGGER.debug("First Name: " + getNewUserFirstName());
      LOGGER.debug("Last Name: " + getNewUserLastName());
      LOGGER.debug("Email Id: " + getNewUserEmailId());
      LOGGER.debug("Password: " + getNewUserPassword());
      
      UserParam userParam = new UserParam();
      userParam.setFirstName(getNewUserFirstName());
      userParam.setLastName(getNewUserLastName());
      userParam.setPrimaryEmail(getNewUserEmailId());
      userParam.setPassword(getNewUserPassword());
      userParam.setCreatedBy("1"); //1 - System Admin
      userParam.setUpdatedBy("1"); //1 - System Admin
      userParam.setUserRole(2); //2 - Registered User
      userParam.setUserType(1); // 1 - External User
      
      String inputXml = null;
      
      try{
          inputXml = CreateXML.generateUserParamXML(userParam);
          WSCaller wsCaller = new WSCaller();
          User user = wsCaller.callSignupNewUserWS(URL.WS_SIGNUP_NEW_USER, inputXml); 
          
          /**
           * Compare user that was entered and what is stored in DB
           */
          if(userParam.getPrimaryEmail().equals(user.getPrimaryEmail())){
              
              EmailContent emailContent = new EmailContent();
              emailContent.setTo("prashanth.nc@orangespan.com");
              emailContent.setFrom("prashanth.nc@gmail.com");
              emailContent.setMessage("This to confirm that the user " + user.getFirstName() +" " + user.getLastName() + " is Created Successfully");
              emailContent.setSubject("Hi, "+ user.getFirstName() +" " + user.getLastName()+" thanks for registering ");
              
              inputXml = CreateXML.generateEmailContentParamXML(emailContent);
              
              wsCaller.callSendEmailNotificationWS(URL.WS_SEND_EMAIL_NOTIFICATION, inputXml);
              
              FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Your Profile Is Created", "Login with your credentials"));
          }
          
      }catch(Exception e){
          e.printStackTrace();
      }
      
      
    }
    public String authenticateUser() {
        LOGGER.debug("Inside authenticateUser()?faces-redirect=true : " + getEmailId() + " : " + getPassword());

        LoginParam loginParam = new LoginParam();
        UserParam userParam = new UserParam();

        loginParam.setEmailId(getEmailId());
        loginParam.setPassword(getPassword());

        FacesContext context = FacesContext.getCurrentInstance();

        LOGGER.debug("Validating User .......................................");
        String inputXml = null;
        List<User> userList = new ArrayList<User>();
        try {

            inputXml = CreateXML.generateLoginParamXML(loginParam);
            LOGGER.debug(inputXml);

            WSCaller wsCaller = new WSCaller();
            //userList = wsCaller.callAuthenticateUserWS(WS_URL_VERIFY_USER, inputXml);
            UserEntitlement userEntitlement = wsCaller.callAuthenticateUserWS(URL.WS_URL_VERIFY_USER, inputXml);

            User user = userEntitlement.getUser();

            LOGGER.debug("Users First Name: " + user.getFirstName());
            LOGGER.debug("Users Last Name: " + user.getLastName());

            if (user != null) {

                LOGGER.debug("User Id: " + user.getUserId());
                LOGGER.debug("Role Id: " + user.getRoleId());

                if (user.getRoleId() == 0) { //Meaning if the logged in user is of ADMIN Group
                    return "admin-dashboard.xhtml?faces-redirect=true";
                } else {
                    SessionObjects sessionObjects = new SessionObjects();

                    //Set User details for the entire session once the login is successful.
                    sessionObjects.setUser(user);
                    sessionObjects.setUserDashboardDetail(userEntitlement.getUserDashboardDetail());

                    // - This sets the flag to decide whether R3 exam can be taken or not...
                    if(userEntitlement.getUserDashboardDetail().getR2status() == 1)
                        sessionObjects.setR2ready(true);

                    context.getExternalContext().getSessionMap().put("SESSION_OBJECT", sessionObjects);
                    this.setUsersFullName(user.getFirstName() + " " + user.getLastName());

                    LOGGER.debug("Credited Points:  " + userEntitlement.getUserDashboardDetail().getCreditedPoints());
                    LOGGER.debug("Days left for Exam:  " + userEntitlement.getUserDashboardDetail().getDaysLeftForExam());
                    LOGGER.debug("Exam Name:  " + userEntitlement.getUserDashboardDetail().getExamDetail().getExamName());
                    LOGGER.debug("Exam Id:  " + userEntitlement.getUserDashboardDetail().getExamDetail().getExamId());
                    LOGGER.debug("Exam Time:  " + userEntitlement.getUserDashboardDetail().getExamDetail().getExamDate());
                    return "registeredUsersDashboard.xhtml?faces-redirect=true";
                }
            } else {
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Login Failure", "Please verify - You have entered Incorrect User Name or Password"));
            }
        } catch (WebServiceException e) {
            e.printStackTrace();
        } catch (Exception ex) {
            ex.printStackTrace();
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Login Failure", "Please verify - You have entered Incorrect User Name or Password"));
        }
        return null;
    }

    public String logout() {

        FacesContext context = FacesContext.getCurrentInstance();

        context.getExternalContext().getSession(false);
        context.getExternalContext().getSessionMap().clear();
        context.getExternalContext().invalidateSession();

        LOGGER.debug("Logging out of NDT.........");

        FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Logout", "Logging out of NDT........."));

        return "index.xhtml?faces-redirect=true";
    }

    /**
     * @return the firstName
     */
    public String getFirstName() {
        return firstName;
    }

    /**
     * @param firstName the firstName to set
     */
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    /**
     * @return the lastName
     */
    public String getLastName() {
        return lastName;
    }

    /**
     * @param lastName the lastName to set
     */
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    /**
     * @return the guestEmailId
     */
    public String getGuestEmailId() {
        return guestEmailId;
    }

    /**
     * @param guestEmailId the guestEmailId to set
     */
    public void setGuestEmailId(String guestEmailId) {
        this.guestEmailId = guestEmailId;
    }

    /**
     * @return the guestFullName
     */
    public String getGuestFullName() {
        return guestFullName;
    }

    /**
     * @param guestFullName the guestFullName to set
     */
    public void setGuestFullName(String guestFullName) {
        this.guestFullName = guestFullName;
    }

    /**
     * @return the newUserFirstName
     */
    public String getNewUserFirstName() {
        return newUserFirstName;
    }

    /**
     * @param newUserFirstName the newUserFirstName to set
     */
    public void setNewUserFirstName(String newUserFirstName) {
        this.newUserFirstName = newUserFirstName;
    }

    /**
     * @return the newUserLastName
     */
    public String getNewUserLastName() {
        return newUserLastName;
    }

    /**
     * @param newUserLastName the newUserLastName to set
     */
    public void setNewUserLastName(String newUserLastName) {
        this.newUserLastName = newUserLastName;
    }

    /**
     * @return the newUserEmailId
     */
    public String getNewUserEmailId() {
        return newUserEmailId;
    }

    /**
     * @param newUserEmailId the newUserEmailId to set
     */
    public void setNewUserEmailId(String newUserEmailId) {
        this.newUserEmailId = newUserEmailId;
    }

    /**
     * @return the newUserPassword
     */
    public String getNewUserPassword() {
        return newUserPassword;
    }

    /**
     * @param newUserPassword the newUserPassword to set
     */
    public void setNewUserPassword(String newUserPassword) {
        this.newUserPassword = newUserPassword;
    }



}
